<!-- 资讯管理 -->
<template>
    <div class="app-container">
        <div class="container user-center">
            <el-row>
                <el-form :model="form" label-width="80px">
                    <el-form-item label="头像">
                        <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                            :on-success="handleAvatarSuccess" accept="image/jpeg">
                            <img v-if="form.headImg" :src="form.headImg" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="邀请码">
                        {{ form.inviteCode }}
                    </el-form-item>
                    <el-form-item label="openId">
                        {{ form.openId }}     <el-button style="margin-left: 10px;" type="primary" @click="userOpenIdClear">重置openId</el-button>
                    </el-form-item>

                    
                    <el-form-item label="邀请链接">
                        {{ inviteUrl }}
                    </el-form-item>
                    <el-form-item label="会员信息" v-if="form.vip">
                        <!-- 订阅类型 -->

                        <div class="flex-center">
                            <div class="vip-type">会员类型：<el-tag>{{ getSubscribeDesc() }}</el-tag></div>
                            <!-- 单独订阅策略 -->
                            <div class="vip-subscribe"
                                v-if="!form.subscribeType && form.subStrategyIds && form.subStrategyIds.length">
                                订阅策略：<el-tag>{{ getStategyNames(form.subStrategyIds) }}</el-tag></div>

                            <!-- 剩余天数 -->
                            <div v-if="form.leftDays">剩余{{ form.leftDays }}天</div>
                            <!-- 到期时间 -->
                            <div v-if="form.memberEndTime">会员到期时间：{{ form.memberEndTime }}</div>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item label="Email">
                        <el-input v-model="form.username" placeholder="Email" clearable :readonly="!isAdd" />
                    </el-form-item> -->
                    <el-form-item label="昵称">
                        {{ form.nickname }}
                    </el-form-item>

                    <el-form-item label="创建时间">
                        {{ form.createTime }}
                    </el-form-item>
                    <el-form-item label="订阅时间">
                        {{ form.subscribeTime }}
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="form.note" placeholder="note" clearable />
                    </el-form-item>
                    <!-- <el-form-item label="用户级别">
                        <el-input v-model="form.memberLevel" placeholder="用户级别 0-9" clearable />
                    </el-form-item> -->
                    <el-form-item label="登录密码">
                        <el-input v-model="form.password" placeholder="登录密码" clearable />
                    </el-form-item>
                    <!-- <el-form-item label="支付密码">
                        <el-input v-model="form.payPassword" placeholder="支付密码" clearable />
                    </el-form-item>
                    <el-form-item label="抽奖中奖项">
                        <el-input v-model="form.luck_items" placeholder="抽奖中奖项（中奖项目id可以多个用,隔开）" clearable />
                    </el-form-item> -->
                    <el-form-item label="状态">
                        <el-select v-model="form.status" placeholder="状态" clearable>
                            <el-option v-for="item in Object.keys(statusDesc)" :label="statusDesc[item]" :key="item"
                                :value="item" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="是否提现">
                        <el-select v-model="form.is_withdraw" placeholder="是否提现" clearable>
                            <el-option label="允许" value="0" />
                            <el-option label="禁止" value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否转账">
                        <el-select v-model="form.is_transfer" placeholder="是否转账" clearable>
                            <el-option label="允许" value="0" />
                            <el-option label="禁止" value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否提现(獎金)">
                        <el-select v-model="form.is_withdraw_reward" placeholder="是否提现" clearable>
                            <el-option label="允许" value="0" />
                            <el-option label="禁止" value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否转账(獎金)">
                        <el-select v-model="form.is_transfer_reward" placeholder="是否转账" clearable>
                            <el-option label="允许" value="0" />
                            <el-option label="禁止" value="1" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="">
                        <el-button type="primary" @click="onSubmit">提交</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
        </div>
        <div class="user-center strategy-setting">

            <div class="setting-title">策略推送配置</div>
            <!-- 策略开关配置        1.到期时间 2.默认配置 3.开关配置 4.邀请人数-->
            <div class="strategy-ul">
                <el-table :data="strategySettingList" style="width: 100%">
                    <el-table-column prop="strategyName" label="策略类型" width="180" />
                    <el-table-column prop="leftDays" label="会员剩余时间" align="center">
                        <template #default="scope">
                            <el-tag v-if="scope.row.leftDays">剩余{{ scope.row.leftDays }}天</el-tag>
                            <el-tag v-else>未订阅</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="推送设置" align="center">
                        <template #default="scope">
                            <el-switch v-if="scope.row.leftDays" :model-value="scope.row.open" @update:model-value="handleChangeOpen"
                                @click="handleSwitchClick(scope.row)" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="setting-title margin20">策略2高低分推送配置</div>
            <div class="checkbox-group" style="margin-bottom: 40px;">
                <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="item in columns" :key="item.value" :label="item.value">{{  item.text }}</el-checkbox>
                </el-checkbox-group>
                <el-button class="margin20" type="primary" @click="handleSaveTime">提交</el-button>
            </div>
            <div class="setting-title margin20">策略3AG趋势推送配置</div>
            <div class="checkbox-group" style="margin-bottom: 40px;">
                <el-checkbox-group v-model="checkList3">
                    <el-checkbox v-for="item in columns" :key="item.value" :label="item.value">{{  item.text }}</el-checkbox>
                </el-checkbox-group>
                <el-button class="margin20" type="primary" @click="handleSaveTime3">提交</el-button>
            </div>

            <div class="setting-title margin20">策略4波段趋势推送配置</div>
            <div class="checkbox-group" style="margin-bottom: 40px;">
                <el-checkbox-group v-model="checkList4">
                    <el-checkbox v-for="item in columns" :key="item.value" :label="item.value">{{  item.text }}</el-checkbox>
                </el-checkbox-group>
                <el-button class="margin20" type="primary" @click="handleSaveTime4">提交</el-button>
            </div>
<!-- 
            <div class="setting-title margin20">我的邀请列表</div>
            <div class="invite-ul margin20">
                <el-table :data="inviteArr" style="width: 100%">
                    <el-table-column prop="username" label="用户名" width="180" />
                    <el-table-column label="用户类型" align="center">
                        <template #default="scope">
                            <el-tag v-if="scope.row.vip">会员</el-tag>
                            <el-tag v-else>普通用户</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="95" align="center">
                        <template #default="scope">
                            <el-tag>{{ statusDesc[scope.row.status] }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="会员信息"  align="center">
                        <template #default="scope">
                            <div class="vip" v-if="scope.row.vip">
                                <el-tag >{{ getSubscribeDesc(scope.row) }}</el-tag>
                                <div>
                                    <el-tag v-if="!scope.row.subscribeType && scope.row.subStrategyIds && scope.row.subStrategyIds.length">{{ getStategyNames(scope.row.subStrategyIds) }}</el-tag>
                                    <div v-if="scope.row.leftDays">剩余{{ scope.row.leftDays }}天</div>
                              
                                    <div v-if="scope.row.memberEndTime">会员到期:{{ scope.row.memberEndTime }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div> -->
            
        </div>
    </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import {
    createOrUpdateInfo,
    getStatus,
    getUserById,
    getMyPushStrategy,
    pushStateUpdate,
    getPushStateByTime,
    updatePushStateByTime,
    userOpenIdClear,
    // getInviteList,
} from '@/api/user'

import { 
    getSettingPush,
    settingPushUpdate,
} from '@/api/push'
import { utilsMixin } from '@/mixin/utils'

import { getUploadImg } from '@/api/dashboard'
export default {
    name: 'UserCreate',
    mixins: [utilsMixin],
    components: { Plus },
    data() {
        return {
            // inviteArr: [],
            checkList: [],
            checkList3: [],
            checkList4: [],
            columns: [
                { text: '5分钟推送', value: '1', select: false },
                { text: '15分钟', value: '2', select: false },
                { text: '30分钟', value: '3', select: false },
                { text: '1小时', value: '4', select: false },
                { text: '2小时', value: '7', select: false },
                { text: '4小时', value: '5', select: false },
                { text: '6小时', value: '8', select: false },
                { text: '12小时', value: '9', select: false },
                { text: '日线', value: '6', select: false },
            ],
            currentStrategy: {},
            strategySettingList: [],
            form: {
                id: '',
                nickname: '',
                email: '',
                payPassword: '',
                password: '',
                status: '0',
                headImg: '',
                is_withdraw: '',
                is_transfer: '',
                is_withdraw_reward: '',
                is_transfer_reward: '',
                luck_items: '',
                note: '',
            },
            isAdd: true,
            uploadUrl: getUploadImg('avatar'),
            statusDesc: getStatus()
        }
    },
    computed: {
        subscribeTypeStr() {
            return this.form.subscribeType ? '一卡通' : '单独订阅';
        },
        strategyList() {
            return this.$store.state.user.strategyList;
        },
        inviteUrl() {
            return `https://www.aiaabiok.com/register?inviteCode=${this.form.inviteCode}`;
        },
    },

    created() {
        if (this.$route.params && this.$route.params.id) {
            this.form.id = this.$route.params.id
            this.isAdd = false
            this.fetchData()
        }


        this.getMyStrategyList();
        this.getTimeCheckList();
        // this.getInviteList();
    },
    methods: {
        fetchData() {
            getUserById(this.form.id).then(response => {
                let data = response.data;
                console.log('====', JSON.parse(JSON.stringify(response.data)))
                Object.assign(this.form, response.data,
                    {
                        status: String(data.status || 0),
                        is_withdraw: String(data.isWithdraw || 0),
                        is_transfer: String(data.isTransfer || 0),
                        is_withdraw_reward: String(data.isWithdrawReward || 0),
                        is_transfer_reward: String(data.isTransferReward || 0)
                    })
            }).catch((e) => {
                console.log(e);
            })
        },

        userOpenIdClear() {
            userOpenIdClear({
                userId: this.form.id
            }).then(res => {
                if (res.code === 20000) {
                    this.$message({ message: 'openId重置成功', type: 'success' });
                }
            })
        },
        // getInviteList() {
        //     getInviteList({
        //         userId: this.form.id
        //     }).then(res => {
        //         if (res.code === 20000) {
        //             this.inviteArr = res.data;
        //         }
        //     })
        // },
        getTimeCheckList() {
            getSettingPush({
                userId: this.form.id,
                strategyId: 2,
            }).then((res) => {
                if (res.code === 20000) {
                    if (!res.data) return;
                    this.checkList = res.data.periodValue.split(',');
                }

            })
            getSettingPush({
                userId: this.form.id,
                strategyId: 3,
            }).then((res) => {
                if (res.code === 20000) {
                    if (!res.data) return;
                    this.checkList3 = res.data.periodValue.split(',');
                }

            })

            getSettingPush({
                userId: this.form.id,
                strategyId: 4,
            }).then((res) => {
                if (res.code === 20000) {
                    if (!res.data) return;
                    this.checkList4 = res.data.periodValue.split(',');
                }

            })
        },
        handleSaveTime() {
            settingPushUpdate({
                userId: this.form.id,
                periods: this.checkList.join(','),
                strategyId: 2,
            }).then((res) => {
                if (res.code === 20000) {
                    this.$message({ message: '周期推送配置修改成功', type: 'success' });
                } 
            }).catch(() => { 
            })
        },
        handleSaveTime3() {
            settingPushUpdate({
                userId: this.form.id,
                periods: this.checkList3.join(','),
                strategyId: 3,

            }).then((res) => {
                if (res.code === 20000) {
                    this.$message({ message: '周期推送配置修改成功', type: 'success' });
                } 
            }).catch(() => { 
            })
        },
        handleSaveTime4() {
            settingPushUpdate({
                userId: this.form.id,
                periods: this.checkList4.join(','),
                strategyId: 4,

            }).then((res) => {
                if (res.code === 20000) {
                    this.$message({ message: '周期推送配置修改成功', type: 'success' });
                } 
            }).catch(() => { 
            })
        },
        getMyStrategyList() {
            console.log('=====', this.form.id)
            getMyPushStrategy({
                userId: this.form.id,
            }).then(res => {
                if (res.code === 20000) {
                    console.log(res);
                    res.data.forEach(item => {
                        item.open = !!item.open;
                    })
                    this.strategySettingList = res.data;
                }
            })
        },
        getSubscribeDesc() {
            if (!this.form.vip) return '';
            if (this.form.subscribeType == 1) {
                return '一卡通';
            } else {
                return '单独订阅';
            }
        },
        getStategyNames(ids) {
            const nameArr = [];
            this.strategyList.forEach(item => {
                if (ids.includes(item.id)) {
                    nameArr.push(item.strategyName);
                }
            });
            return nameArr.join(',')
        },
        // 查询
        onSearch() {
            this.listQuery = Object.assign(this.listQuery, this.listQueryParam) // 合并对象
            this.fetchData()
        },
        handleAvatarSuccess(response) {
            if (response && response.success) {
                this.form.headImg = response.data
            }
        },
        onSubmit() {
            createOrUpdateInfo(this.form).then(respones => {
                // this.form.id = respones.data
                this.$message({ message: '保存成功', type: 'success' })
            }).catch(() => {

            })
        },

        handleSwitchClick(item) {
            this.currentStrategy = item;
        },
        handleChangeOpen(value) {
            console.log(value)
            if (!value) {
                // 关闭的时候给对应提示

                ElMessageBox.confirm(
                '关闭策略后，公众号将不在推送该策略，想要收到实时推送，请重新打开。',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    this.$nextTick(() => {
                        pushStateUpdate({
                            strategyId: this.currentStrategy.id,
                            status: value ? 1 : 0,
                            userId: this.form.id,
                        }).then(res => {
                            if (res.code === 20000) {
                                this.$message({ message: '推送已经关闭', type: 'success' });
                                this.currentStrategy.open = false;
                            }
                        })
                    })
                });
                // showConfirmDialog({
                //     title: '温馨提示',
                //     message: '关闭策略后，公众号将不在推送该策略，想要收到实时推送，请重新打开。',
                // }).then(() => {
                //     console.log('=====', this.currentStrategy)
                //     this.$nextTick(() => {
                //         pushStateUpdate({
                //             strategyIds: this.currentStrategy.id,
                //             status: value ? 1 : 0,
                //         }).then(res => {
                //             if (res.code === 20000) {
                //                 showSuccessToast('推送已经关闭');
                //                 this.currentStrategy.open = false;
                //             }
                //         })
                //     })
                // });

            } else {
                this.$nextTick(() => {
                    pushStateUpdate({
                        strategyId: this.currentStrategy.id,
                        status: value ? 1 : 0,
                        userId: this.form.id,
                    }).then(res => {
                        if (res.code === 20000) {
                            this.$message({ message: '推送已经打开', type: 'success' });
                            this.currentStrategy.open = true;
                        }
                    })
                });

            }

        },

        pushStrategySet() {
            pushStrategySetting({
                strategyId: item.id, // 策略id
                status: item.status, //状态 0 关闭 1开启
                userId: this.form.id,
            }).then(res => {

            })
        }
    }
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.flex-center {
    display: flex;
    flex-direction: column;
}

.user-center {
    padding-left: 40px
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.margin20 {
    margin: 20px 0;
}
</style>